﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace DataTier
{
    public class MailHandler
    {
        private SmtpClient client;

        public MailHandler()
        {
            client = new SmtpClient();
            client.Host = "send.one.com";
            client.Port = 2525;
            client.EnableSsl = true;
            client.UseDefaultCredentials = false;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials = new NetworkCredential("peter@danskejendomsforvaltning.dk", "Capacent");

        }
        public void SendMail(string htmlInput, string subject, string serverPath, Dictionary<string, string> addr, List<Klage_billede> billeder)
        {
            var from = new MailAddress("peter@danskejendomsforvaltning.dk", "Dansk Ejendomsforvaltning");
            var to = new MailAddress(addr["toAddr"], addr["toName"]);
            var replyTo = new MailAddress("mail@danskejendomsforvaltning.dk", "Dansk Ejendomsforvaltning");
            var msg = new MailMessage(from, to);

            var ccAddrs = addr["ccAddr"].Split(',');
            var ccNames = addr["ccName"].Split(',');
            if (ccAddrs.Length != ccNames.Length)
                throw new ArgumentException("CC adresser stemmer ikke overens med cc navne. Der skal være lige mange. Check web.config");
            for (int i = 0; i < ccAddrs.Length; i++)
            {
                var cc = new MailAddress(ccAddrs[i], ccNames[i]);
                msg.CC.Add(cc);
            }
            msg.Subject = subject;
            msg.ReplyToList.Add(replyTo);
            msg.IsBodyHtml = true;
            msg.Body = htmlInput;
            foreach (var billede in billeder)
            {
                msg.Attachments.Add(new Attachment(serverPath + billede.PictureLinkStr));

            }

            client.SendCompleted += (s, e) =>
            {
                client.Dispose();
                msg.Dispose();
            };
            client.SendAsync(msg, null);
        }
    }

}
